/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.tools.idea.lint.common

import com.android.ide.common.gradle.Dependency.Companion.parse
import com.android.tools.idea.lint.common.LintBundle.Companion.message
import com.android.tools.lint.checks.GradleDetector
import com.android.tools.lint.checks.GradleDetector.Companion.KEY_COORDINATE
import com.android.tools.lint.checks.GradleDetector.Companion.KEY_REVISION
import com.android.tools.lint.detector.api.Incident
import com.android.tools.lint.detector.api.LintFix.Companion.create
import com.android.tools.lint.detector.api.LintFix.Companion.getString
import com.intellij.psi.PsiElement

class AndroidLintGradleDynamicVersionInspection :
  AndroidLintInspectionBase(
    message("android.lint.inspections.gradle.dynamic.version"),
    GradleDetector.PLUS,
  ) {
  override fun getQuickFixes(
    startElement: PsiElement,
    endElement: PsiElement,
    incident: Incident,
  ): Array<LintIdeQuickFix> {
    val fixData = incident.fix
    val gc = getString(fixData, KEY_COORDINATE, null)
    val revision = getString(fixData, KEY_REVISION, null)
    if (fixData == null || gc == null || revision == null) {
      return super.getQuickFixes(startElement, endElement, incident)
    }
    val newFix =
      create().replace().name("Replace with specific version").text(gc).with("placeholder").build()
    return arrayOf(
      newFix.toIdeFix(startElement.project, incident) { _, _ ->
        val dependency = parse(gc)
        val resolved =
          LintIdeSupport.get().resolveDynamicDependency(startElement.project, dependency)
        if (resolved == null) {
          gc
        } else {
          "${dependency.group}:${dependency.name}:$resolved"
        }
      }
    )
  }
}
